package com.example.previewvideo.util;

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * author : 浪
 * date :2024/9/14 14:54
 * desc:
 */
public class VideoBuffer {
    private MediaCodec mediaCodec;
    private boolean isRecording;
    private ByteArrayOutputStream byteArrayOutputStream;

    public void startRecording() throws IOException {
        MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 640 ,480);
        format.setInteger(MediaFormat.KEY_BIT_RATE, 10000000);
        format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
        format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
        format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10);

        mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
        mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
        mediaCodec.start();
        isRecording = true;
        byteArrayOutputStream = new ByteArrayOutputStream();

        new Thread(() -> {
            while (isRecording) {
                MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
                int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000);
                if (outputBufferIndex >= 0) {
                    ByteBuffer outputBuffer = mediaCodec.getOutputBuffer(outputBufferIndex);
                    byte[] data = new byte[bufferInfo.size];
                    outputBuffer.get(data);
                    try {
                        byteArrayOutputStream.write(data);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
                }
            }
        }).start();
    }

    public void stopRecording() {
        isRecording = false;
        mediaCodec.stop();
        mediaCodec.release();
    }

    public byte[] getRecordedData() {
        return byteArrayOutputStream.toByteArray();
    }
}
